import os
from openpyxl import Workbook



class Converter:
    """
    txt文件转化为xlsx表格，
    """
    def __init__(self, txt_file_path=None, txt_file_directory=None,absu=False):
        self.first_unit = "s"
        self.second_unit = "μm"
        self.absolute = absu
        self.lines = None
        self.txt_file_path = txt_file_path
        self.txt_file_directory = txt_file_directory
        self.wb = Workbook()
        self.ws = self.wb.active
        self.head = dict()
        self.write_head()

    def write_head(self):
        for i, (key, value) in enumerate(self.head.items()):
            self.ws.cell(column=i+1, row=1, value=key)
            self.ws.cell(column=i+1, row=2, value=value)

    def load_txt_directory(self):
        for i, txt_file_path in enumerate(self.txt_file_directory):
            self.txt_file_path = txt_file_path
            self.load_txt_file(i)
            # 在最后一个txt文件写入后保存xlsx文件
            if i == len(self.txt_file_directory) - 1:
                self.wb.save(f"{self.txt_file_path}.xlsx")

    def load_txt_file(self, i=0):
        txt_file = open(self.txt_file_path, 'r')
        self.lines = txt_file.readlines()
        self.write_xlsx_file(i)

    def write_xlsx_file(self, i=0):
        # 写入表头
        self.ws.cell(row=1, column=i + 2, value=self.first_unit)
        self.ws.cell(row=2, column=i + 2, value=self.second_unit)
        for index, meta_time_data in enumerate(self.lines):
            print(1)
            if i == 0:
                self.ws.cell(row=index + 3, column=1, value=meta_time_data.strip().split("\t")[0])  # 时间time
            if self.absolute is True:
                self.ws.cell(row=index + 3, column=i + 2, value=abs(float(meta_time_data.strip().split("\t")[-1])))  # 数据data
            if self.absolute is False:
                self.ws.cell(row=index + 3, column=i + 2, value=meta_time_data.strip().split("\t")[-1])  # 数据data



if __name__ == '__main__':
    tp = r"E:\20250526 漫湾转轮动应力&稳定性试验\20250429 大轴应力必创数据\txt绝对时间格式\2105\2105-20MW.txt"
    myConverter = Converter(txt_file_path=tp)
    myConverter.first_unit = "time"
    myConverter.second_unit = "με"
    myConverter.load_txt_file()
